import {loginByEmail,logout,getInfo,getUserType} from 'api/login';
import {getToken,setToken,removeToken} from 'utils/auth';
import { Base64 } from 'js-base64';
import {Message, MessageBox} from 'element-ui';
import { queryIndustry } from "api/businessManagement/merchant/index";

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: localStorage.getItem("access-token"),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    menus: undefined,
    elements: undefined,
    setting: {
      articlePlatform: []
    },
    userId:'',
    distributorId:'',
    companyId:'',
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction;
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting;
    },
    SET_STATUS: (state, status) => {
      state.status = status;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus;
    },
    SET_ELEMENTS: (state, elements) => {
      state.elements = elements;
    },
    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user = '';
    },
    
    SET_USERID: (state, userId) => {
      state.userId = userId;
    },
    SET_DISTRIBUTORID: (state, distributorId) => {
      state.distributorId = distributorId;
    },
    SET_COMPANYID: (state, companyId) => {
      state.companyId = companyId;
    },
  },

  actions: {
    // 邮箱登录
    LoginByEmail({
      commit
    }, userInfo) {
      const phone = userInfo.phone.trim();
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      commit('SET_MENUS', undefined);
      commit('SET_ELEMENTS', undefined);
      removeToken();
      return new Promise((resolve, reject) => {
      	//发送邮箱登录的请求
        loginByEmail(phone, userInfo.password).then(response => {
        	if(response.code == '0'){
        		const data = response;
	          //base64 将返回的数据截取中间一段再解码
	          const access = JSON.parse(Base64.decode(data.value.split('.')[1]));
	          //获取token接口返回的数据解码之后打印出来
//	          console.log('token的信息');
//	          console.log(access);
						localStorage.setItem("access-token",data.value);
            localStorage.setItem('access-userId',access.userId);
            localStorage.setItem("distributorId",access.distributorId);
            localStorage.setItem("companyId",access.companyId);
            localStorage.setItem("userType",access.userType);
            
//          commit('SET_USERID', access-userId);
//          commit('SET_DISTRIBUTORID', access.distributorId);
//          commit('SET_COMPANYID', access.companyId);
            queryIndustry(localStorage.getItem("locale") === "en" ? "1" : "0").then(res=>{
              localStorage.setItem('queryIndustryObj',JSON.stringify(res.value));
            })
            getUserType(access.userId).then(res=>{
              localStorage.setItem('userName',res.value.attr2);
            });
						const timeId = setTimeout(function(){
							localStorage.removeItem('access-token');
							localStorage.removeItem('access-userId');
							clearTimeout(timeId)
						},7200000)
	          setToken(data.value);
	          commit('SET_TOKEN', data.value);
        	}else if(response.code == '2'){
        			let errMsg;
        			if(localStorage.getItem('locale') === 'zh_cn'){
					    	 errMsg = '用户不存在';
//					    	 timeMsg = '密码错误，请重新登录';
					    }else if(localStorage.getItem('locale') === 'zh_tw'){
					    	 errMsg = '用戶不存在';
//					    	 timeMsg = '密碼錯誤，請重新登入';
					    }else{
					    	 errMsg = 'Username does not exist';
//					    	 timeMsg = 'Password incorrect, please re-enter';
					    }
	        		Message({
					      message: errMsg,
					      type: 'error',
					      duration: 5 * 1000
			    	})
        	}else if(response.code == '11'){
        			let timeMsg;
        			if(localStorage.getItem('locale') === 'zh_cn'){
					    	 timeMsg = '密码错误，请重新登录';
					    }else if(localStorage.getItem('locale') === 'zh_tw'){
					    	 timeMsg = '密碼錯誤，請重新登入';
					    }else{
					    	 timeMsg = 'Password incorrect, please re-enter';
					    }
	        		Message({
					      message: timeMsg,
					      type: 'error',
					      duration: 5 * 1000
			    	})
        	}else if(response.code == '5'){
        			let disabledMsg;
        			if(localStorage.getItem('locale') === 'zh_cn'){
					    	 disabledMsg = '该账号已被停用';
					    }else if(localStorage.getItem('locale') === 'zh_tw'){
					    	 disabledMsg = '該賬號已被停用';
					    }else{
					    	 disabledMsg = 'This account has been disabled';
					    }
	        		Message({
					      message: disabledMsg,
					      type: 'error',
					      duration: 5 * 1000
			    	})
        	}
	          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 获取用户信息
    GetInfo({commit,state}) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response;
          //获取用户信息接口返回的数据
//        console.log('用户信息接口返回的数据')
//        console.log(data)
          commit('SET_ROLES', 'admin');
          commit('SET_NAME', data.value.username);
          commit('SET_AVATAR', 'http://git.oschina.net/uploads/42/547642_geek_qi.png?1499487420');
          commit('SET_INTRODUCTION', data.value.username);
          const menus = {};
//        console.log(data.value.menus)
          for (let i = 0; i < data.value.menus.length; i++) {
            menus[data.value.menus[i].code] = true;
          }
//					console.log(menus)
          commit('SET_MENUS', menus);
          const elements = {};
          for (let i = 0; i < data.value.elements.length; i++) {
            elements[data.value.elements[i].code] = true;
          }
//        console.log(elements)
          commit('SET_ELEMENTS', elements);
          resolve(data);
        }).catch(error => {
//      	console.log(199);
          reject(error);
        });
      });
    },

    // 第三方验证登录
    LoginByThirdparty({
      commit,
      state
    }, code) {
      return new Promise((resolve, reject) => {
        commit('SET_CODE', code);
        loginByThirdparty(state.status, state.email, state.code).then(response => {
          commit('SET_TOKEN', response.data.token);
          setToken(response.data.token);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    LogOut({commit,state}) {
      return new Promise((resolve, reject) => {
      	this.$router.push({path:'/dashboard'})
//      logout(state.token).then(() => {
//        commit('SET_TOKEN', '');
//        commit('SET_ROLES', []);
//        commit('SET_MENUS', undefined);
//        commit('SET_ELEMENTS', undefined);
//        removeToken();
//        resolve();
//      }).catch(error => {
//        reject(error);
//      });
      });
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_MENUS', undefined);
        commit('SET_ELEMENTS', undefined);
        removeToken();
        resolve();
      });
    },

    // 动态修改权限
    ChangeRole({
      commit
    }, role) {
      return new Promise(resolve => {
        commit('SET_ROLES', [role]);
        commit('SET_TOKEN', role);
        setToken(role);
        resolve();
      })
    }
  }
};

export default user;
